/**
 * 
 */
package com.csc.bankingsystem.web.spring.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.csc.bankingsystem.core.dao.UserInfoDAO;
import com.csc.bankingsystem.core.entity.UserInfo;
import com.csc.bankingsystem.core.entity.UserInfoRole;

/**
 * @author angelkid
 *
 */
public class CustomUserDetailsService implements UserDetailsService {

	@Autowired
	private UserInfoDAO userInfoDAO;

	public UserDetails loadUserByUsername(String login)
			throws UsernameNotFoundException {
		UserInfo domainUser = userInfoDAO.getUserInfoByLoginId(login);
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		return new User(domainUser.getLoginId(), domainUser.getPassword(),
				enabled, accountNonExpired, credentialsNonExpired,
				accountNonLocked, getAuthorities(domainUser.getUserInfoRoles()));
	}

	public Collection getAuthorities(List<UserInfoRole> userInfoRoles) {
		List<String> roles = new ArrayList<String>();
		for (UserInfoRole elem : userInfoRoles) {
			roles.add(elem.getUserRole().getRole().toString());
		}
		List authList = getGrantedAuthorities(roles);
		return authList;
	}

	public static List getGrantedAuthorities(List<String> roles) {
		List authorities = new ArrayList();
		for (String role : roles) {
			authorities.add(new SimpleGrantedAuthority(role));
		}
		return authorities;
	}
}
